using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace AutoUpdater
{
    public static class FileChecker
    {
        /// <summary>
        /// 带详细日志的MD5校验
        /// </summary>
        public static bool VerifyMD5WithDetail(string filePath, string expectedMd5)
        {
            try
            {
                Logger.Info($"开始MD5校验：文件={filePath}, 期望MD5={expectedMd5}");

                if (!File.Exists(filePath))
                {
                    Logger.Error($"MD5校验失败：文件不存在，路径={filePath}");
                    return false;
                }

                FileInfo fileInfo = new FileInfo(filePath);
                if (fileInfo.IsReadOnly)
                {
                    Logger.Warn($"MD5校验警告：文件为只读属性，尝试移除...");
                    fileInfo.Attributes &= ~FileAttributes.ReadOnly;
                }

                string actualMd5 = CalculateMD5(filePath);
                Logger.Info($"MD5校验：实际MD5={actualMd5}, 期望MD5={expectedMd5}");

                bool result = string.Equals(
                    actualMd5?.Trim().Replace("-", ""), 
                    expectedMd5?.Trim().Replace("-", ""), 
                    StringComparison.OrdinalIgnoreCase
                );

                if (result)
                {
                    Logger.Info("MD5校验通过");
                }
                else
                {
                    Logger.Error($"MD5校验失败：实际值与期望值不匹配");
                    Logger.Error($"MD5长度对比：实际={actualMd5?.Length}字符, 期望={expectedMd5?.Length}字符");
                }

                return result;
            }
            catch (IOException ex)
            {
                Logger.Error($"MD5校验失败（文件访问错误）: {ex.Message}，可能是文件被占用");
                return false;
            }
            catch (UnauthorizedAccessException ex)
            {
                Logger.Error($"MD5校验失败（权限错误）: {ex.Message}，请确认程序有读取权限");
                return false;
            }
            catch (Exception ex)
            {
                Logger.Error($"MD5校验失败（未知错误）: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 计算文件MD5
        /// </summary>
        public static string CalculateMD5(string filePath)
        {
            using (var md5 = MD5.Create())
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
            {
                byte[] hashBytes = md5.ComputeHash(stream);
                return BitConverter.ToString(hashBytes).Replace("-", "").ToUpperInvariant();
            }
        }

        /// <summary>
        /// 兼容旧版的MD5校验方法
        /// </summary>
        public static bool VerifyMD5(string filePath, string expectedMd5)
        {
            return VerifyMD5WithDetail(filePath, expectedMd5);
        }
    }
}
    